import React from 'react'
import AdvancedTable from 'components/advanced-table'
import httpFetch from 'share/httpFetch'
import errorMessage from "share/errorMessage";
import moment from 'moment'
import { queryCurrencyPrecision } from "share/common";
import { Popover, Button } from "antd";

const advancedTableService = {
  getFinanceExpenseReports: (page, size, status, searchParams) =>
    httpFetch.post(`/api/v2/expense/reports/finance/admin/search?page=${page}&size=${size}`, {
      ...searchParams,
      status
    }).catch(err => {
      errorMessage(err.response);
      throw err;
    }),
  getExpenseList: (page, size, expenseTypeIds = []) =>
    httpFetch.post(`/api/invoices/my`, { page, size, expenseTypeIds })
      .catch(err => {
        errorMessage(err.response);
        throw err;
      })
};


export default {
  key: 'advanced-table',
  name: 'AdvancedTable 高级表格',
  author: '张然',
  description: '整合::AdvancedSearch::和::Table::，封装一个高级数据展示表格。',
  isExampleFull: true,
  api: [
    {
      title: 'API',
      data: [{
        param: 'title', description: '标题。', type: 'string|ReactNode', defaultValue: '-'
      }, {
        param: 'index', description: '是否需要序号字段列。', type: 'boolean', defaultValue: 'false'
      }, {
        param: 'service', description: '表格调用远程数据的::service::，其中参数::page::页码、::size::页面数目、::searchParams::表格内::AdvancedSearchFormItem::和::AdvancedSearch::的结果、::extraParams::传入的额外参数。', type: 'function(page, size, searchParams, extraParams)', defaultValue: '-'
      }, {
        param: 'searchForm', description: '::AdvancedSearch::的::searchForm::。', type: 'searchItem[]', defaultValue: '[]'
      }, {
        param: 'columns', description: '::Table::的::columns::，如果次对象参数内带有::searchForm::，则会覆盖原有::filterDropdown::，根据配置渲染一组::AdvancedSearchFormItem::。', type: 'column[]', defaultValue: '[]'
      }, {
        param: 'expandedRowRender', description: '表格展开配置，同::Table::。', type: 'function(record)', defaultValue: '() => null'
      }, {
        param: 'expandAll', description: '是否需要展开所有按钮。', type: 'boolean', defaultValue: 'false'
      }, {
        param: 'rowSelection', description: '表格选择配置，同::Table::。', type: 'rowSelection', defaultValue: '-'
      }, {
        param: 'extraParams', description: '调用::service::时额外给予的参数(相比这个参数，其他参数更建议直接在页面封装service处理)。', type: 'object', defaultValue: '-'
      }, {
        param: 'onGetData', description: '内部获取列表数据后的回调。', type: 'function(dataSource, pagination, searchParams)', defaultValue: '-'
      }, {
        param: 'onGetDataError', description: '内部获取列表数据出错后的回调。', type: 'function(e, pagination, searchParams)', defaultValue: '-'
      }, {
        param: 'footer', description: '底部的额外内容。', type: 'ReactNode', defaultValue: '-'
      }, {
        param: 'pinnedList', description: '内部::AdvancedSearcher::的::pinnedList::。', type: 'array', defaultValue: '[]'
      }, {
        param: 'tableScrollMinHeight', description: '内部表格最小高度，如果内部计算得出表格高度小于此高度时，内部将会增加滚动。', type: 'number', defaultValue: '300'
      }, {
        param: 'tableName', description: '当设置此值时，将会增加列保存、内部::AdvancedSearch::的对应::tableName::附加的功能，这些功能都有对应后台交互，使用时请注意，有业务需求再增加此字段。如果设置，请保证全项目唯一。', type: 'string', defaultValue: '-'
      }],
      description: '该表格需要有一个有高度的父组件包裹，内部表格高度都是根据此值计算得出。'
    }
  ],
  example: [
    {
      title: '基础用法',
      description: '高度固定，上下固定内容滚动。内部由::AdvancedSearch::和::Table::组成，::Table::的列筛选可以通过配置列::searchForm::进行自定义。',
      state: {
        index: true,
        title: '单据审核',
        searchForm: [{
          id: 'approvalDate', label: '审批日期', component: 'DateRangePicker',
          props: {
            placeholder: '请选择',
          },
          parser: value => ({
            approvalStartDate: (value && value[0]) ? value[0].format('YYYY-MM-DD 00:00:00') : null,
            approvalEndDate: (value && value[1]) ? value[1].format('YYYY-MM-DD 23:59:59') : null
          })
        }, {
          id: 'legalEntity', label: '法人实体', component: 'Chooser',
          props: {
            type: 'corporation_entity',
            placeholder: '请选择',
            valueKey: 'companyReceiptedOID',
            labelKey: 'companyName'
          },
          parser: value => ({
            corporationOIDs: value ? value.map(item => item.companyReceiptedOID) : null
          })
        }, {
          id: 'applicantOID', label: '申请人', component: 'Selector',
          dataIndex: 'applicantName',
          props: {
            placeholder: '请选择',
            type: 'user',
            showSearch: true,
            searchIfKeywordIsNull: true
          }
        }, {
          id: 'formOIDs', label: '单据类型', component: 'Searcher',
          dataIndex: 'formName',
          props: {
            placeholder: '请选择',
            type: 'authority_form',
            listExtraParams: { formType: 1002 },
            labelKey: 'formName',
            descriptionKey: 'companyName'
          },
          parser: value => ({
            formOIDs: value ? value.map(item => item.formOID) : null
          })
        }, {
          id: 'dateRange', label: '提交日期', component: 'DateRangePicker',
          dataIndex: 'submittedDate',
          props: {
            placeholder: '请选择',
          },
          parser: value => ({
            startDate: (value && value[0]) ? value[0].format('YYYY-MM-DD 00:00:00') : null,
            endDate: (value && value[1]) ? value[1].format('YYYY-MM-DD 23:59:59') : null
          })
        }],
        columns: [{
          dataIndex: 'applicantName', title: '申请人', width: '15%'
        }, {
          dataIndex: 'formName', title: '单据类型'
        }, {
          dataIndex: 'childBusinessCode', title: '报销单号'
        }, {
          dataIndex: 'submittedDate', title: '提交日期', width: 120,
          render: date => moment(date).format('YYYY-MM-DD')
        }],
        expandedRowRender: record => record.warningList ?
          <p>{JSON.parse(record.warningList).map(item => item.message).join(',')}</p> :
          null,
        extraParams: {
          status: 'prending_audit'
        },
        service: (page, size, searchParams, extraParams) =>
          advancedTableService.getFinanceExpenseReports(page, size, extraParams.status, searchParams)
      },
      getMethod: context => {
        return {}
      },
      getContent: context => {
        return (
          <div style={{ height: 768, width: '100%' }}>
            <AdvancedTable {...context.state} onGetData={console.log}/>
          </div>
        )
      }
    },{
      title: '带选择的和操作按钮例子',
      description: '带选择，外部传入::rowSelection::。表格上方的操作空间直接使用::children::进行传入，底部区域通过::footer::进行传入。',
      state: context => ({
        index: true,
        title: '我的账本',
        searchForm: [{
          id: 'expenseTypeIds', label: '费用类型', component: 'Searcher',
          dataIndex: 'expenseTypeName',
          props: {
            placeholder: '请选择',
            searcherItem: {
              url: '/api/expense/type/company/all/icons',
              title: '选择费用类型',
              key: 'id'
            },
            labelKey: 'name',
            showDetail: true
          },
          parser: value => ({
            expenseTypeIds: value ? value.map(item => item.id) : null
          })
        }],
        columns: [{
          title: '费用类型', dataIndex: 'expenseTypeName'
        }, {
          title: '日期', dataIndex: 'createdDate', width: 120,
          render: createdDate => new Date(createdDate).format('yyyy-MM-dd')
        }, {
          title: '币种', dataIndex: 'invoiceCurrencyCode', width: 72
        }, {
          title: '金额', dataIndex: 'amount', align: 'right',  width: 72,
          render: (value,item) => context.filterMoney(value, queryCurrencyPrecision(item.invoiceCurrencyCode))
        }, {
          title: '本位币金额', align: 'right',dataIndex: 'baseAmount',
          render: value => context.filterMoney(value, queryCurrencyPrecision(''))
        }, {
          title: '费用归属人', dataIndex: 'owner',
          render: (value, record) => {
            let showValue = value && value.fullName;
            if (
              showValue &&
              record.reimbursementUserOID &&
              record.ownerOID &&
              record.reimbursementUserOID !== record.ownerOID
            )
              showValue += `（已转交：${record.reimbursementUserName}）`;
            return showValue ? <Popover content={showValue}>{showValue}</Popover> : '-'
          }}],
        expandedRowRender: context.renderAllExpandedRow,
        service: (page, size, searchParams) =>
          advancedTableService.getExpenseList(page, size, searchParams.expenseTypeIds),
        rowSelection: {
          selectedRowKeys: [],
          onChange: context.onSelectChange
        }
      }),
      getMethod: context => {
        return {
          renderAllExpandedRow: record => {
            let result = [];
            let infoRes = [];
            let types = record.invoiceLabels || [];
            let lastIndex = -1;
            types.map((label, index) => {
              if (label.level !== 'INFO') {
                result.push(<span key={index}>{label.name}/</span>);
              } else {
                lastIndex = label.name;
                infoRes.push(<span key={index}>{label.name}/</span>);
              }
            });
            let infoLength = infoRes.length;
            infoLength > 0 && (infoRes[infoLength - 1] = <span key="lastIndex">{lastIndex}</span>);
            result.push(infoRes);
            return result.length > 0 ? result :  null;
          },
          onSelectChange: selectedRowKeys => {
            const { rowSelection } = context.state;
            rowSelection.selectedRowKeys = selectedRowKeys;
            context.setState({ rowSelection });
          }
        }
      },
      getContent: context => {
        const { rowSelection } = context.state;
        return (
          <div style={{ height: 768, width: '100%' }}>
            <AdvancedTable
              {...context.state}
              onGetData={console.log}
              footer={(
                <div>
                  <Button disabled={rowSelection.selectedRowKeys.length === 0}>转交</Button>
                </div>
              )}
            >
              <div style={{ marginBottom: 10 }}>
                <Button>新建费用</Button>
              </div>
            </AdvancedTable>
          </div>
        )
      }
    }
  ]
}
